﻿using ClassLibrary;
using Manager.Properties;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Data.SqlClient;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Web.Security;
using System.Windows.Forms;
using UboxUI;

namespace Manager
{
    public partial class FrmManagerLogin : FrmFather
    {
        public FrmManagerLogin()
        {
            InitializeComponent();
            #region 視窗初始化
            this.LblTitle.Text = this.Text;
            this.LblTitle2.Text = LblTitle.Text;
            this.BtnClose.Left = this.Width - this.BtnClose.Width - 10;
            this.BtnNarrow.Left = this.BtnClose.Left - this.BtnNarrow.Width - 10;
            this.panel1.Top = 0;
            this.panel2.Top = this.panel1.Height;
            #endregion
        }

        private void FrmManagerLogin_Load(object sender, EventArgs e)
        {
            TxtPassword.UseSystemPasswordChar = !TxtPassword.UseSystemPasswordChar;
            /*TxtPassword.Focus();設定焦點*/
        }

        private void BtnExit_Click(object sender, EventArgs e)
        {
            Application.Exit();
        }

        private void BtnLogin_Click(object sender, EventArgs e)
        {
            int check = 0;//輸入與登入檢查
            int userrandom = 0;
            try
            {
                #region SQL 取得亂數

                string strsql = @"	
	                         if exists(select manager_password_random from Manager where manager_username=@Username)
                                begin
	                            set @Randomnum=(select manager_password_random from Manager where manager_username=@Username)
	                            set @Usernum=1
                                end
                             else
                                set @Usernum=0
                                 ";

                #endregion

                #region SQL 管理者登入

                string strsql2 = @"
                                 select manager_id,
		                                manager_first_name,
		                                manager_last_name,
		                                manager_level,
		                                manager_image  
		                        from Manager 
                                where manager_username=@Username
                                and manager_password=@Password
                             ";
                #endregion

                #region 連線設定

                string strconn = Settings.Default.strConn.ToString();
                SqlConnection conn = new SqlConnection(strconn);

                #endregion

                #region step1檢查輸入

                if (TxtUsername.Text == "")
                {
                    check = 1;
                    throw new Exception("帳號未輸入完畢");
                }
                else if (TxtPassword.Text == "")
                {
                    check = 1;
                    throw new Exception("密碼未輸入完畢");
                }

                #endregion

                #region step2取得亂數

                #region cmd設定

                SqlCommand cmd;
                cmd = new SqlCommand(strsql, conn);
                cmd.CommandType = CommandType.Text;

                #endregion

                #region Input變數

                SqlParameter Username = new SqlParameter("@Username", SqlDbType.NVarChar, 20);
                Username.Direction = ParameterDirection.Input;
                Username.Value = this.TxtUsername.Text;
                cmd.Parameters.Add(Username);

                #endregion

                #region Output變數

                SqlParameter usernum = new SqlParameter("@Usernum", SqlDbType.Int, 1);
                usernum.Direction = ParameterDirection.Output;
                cmd.Parameters.Add(usernum);

                SqlParameter randomnum = new SqlParameter("@Randomnum", SqlDbType.Int, 1);
                randomnum.Direction = ParameterDirection.Output;
                cmd.Parameters.Add(randomnum);

                #endregion

                #region 執行
                try
                {
                    conn.Open();
                    cmd.ExecuteNonQuery();
                }
                catch
                {
                    throw new Exception("連線失敗");
                }
                check = Convert.ToInt16(cmd.Parameters["@Usernum"].Value);
                if (check == 1)
                {
                    userrandom = Convert.ToInt32(cmd.Parameters["@Randomnum"].Value);
                }
                else
                {
                    throw new Exception("登入失敗");
                }
                cmd.Dispose();
                conn.Close();
                #endregion

                #endregion

                #region step3登入帳號

                #region cmd設定

                cmd = new SqlCommand(strsql2, conn);
                cmd.CommandType = CommandType.Text;

                #endregion

                #region Input變數

                SqlParameter Username2 = new SqlParameter("@Username", SqlDbType.NVarChar, 20);
                Username2.Direction = ParameterDirection.Input;
                Username2.Value = this.TxtUsername.Text;
                cmd.Parameters.Add(Username2);

                SqlParameter Password = new SqlParameter("@Password", SqlDbType.NVarChar, 20);
                Password.Direction = ParameterDirection.Input;
                Password.Value = FormsAuthentication.HashPasswordForStoringInConfigFile(this.TxtPassword.Text + userrandom.ToString(), "sha1");
                cmd.Parameters.Add(Password);

                #endregion

                #region 執行
                SqlDataReader dr;
                try
                {
                    conn.Open();
                    dr = cmd.ExecuteReader();
                }
                catch
                {
                    cmd.Dispose();
                    conn.Close();
                    conn.Dispose();
                    throw new Exception("連線失敗");
                }
                if (dr.Read())
                {
                    login.managerID = Convert.ToInt32(dr["manager_id"]);
                    login.name = Convert.ToString(dr["manager_first_name"]) + Convert.ToString(dr["manager_Last_name"]);
                    login.level = Convert.ToInt16(dr["manager_level"]);
                    login.username = this.TxtUsername.Text;
                    /*傳圖給FrmManagerMenu*/
                    byte[] buf = (byte[])dr["manager_image"];
                    FrmManagerMenu.buf = (byte[])dr["manager_image"];
                    this.Close();
                    login.username = TxtUsername.Text;
                }
                else
                {
                    throw new Exception("登入失敗");
                }
                #endregion

                #endregion
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        private void TxtUsername_KeyPress(object sender, KeyPressEventArgs e)
        {
            try
            {
                if (e.KeyChar == ' ')
                {
                    e.Handled = true;
                    throw new Exception("不能輸入空白");
                }/*寫在KeyDown無效*/
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        private void TxtPassword_KeyPress(object sender, KeyPressEventArgs e)
        {
            try
            {
                if (e.KeyChar == ' ')
                {
                    e.Handled = true;
                    throw new Exception("不能輸入空白");
                }/*寫在KeyDown無效*/
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }


        #region 按鈕的樣式

        private void BtnLogin_MouseEnter(object sender, EventArgs e)
        {
            this.BtnLogin.FlatAppearance.BorderSize = 0;
            this.BtnLogin.ForeColor = Color.White;
        }

        private void BtnLogin_MouseLeave(object sender, EventArgs e)
        {
            this.BtnLogin.FlatAppearance.BorderSize = 1;
            this.BtnLogin.ForeColor = Color.Black;
        }

        private void BtnExit_MouseEnter(object sender, EventArgs e)
        {
            this.BtnExit.FlatAppearance.BorderSize = 0;
            this.BtnExit.ForeColor = Color.White;
        }

        private void BtnExit_MouseLeave(object sender, EventArgs e)
        {
            this.BtnExit.FlatAppearance.BorderSize = 1;
            this.BtnExit.ForeColor = Color.Black;
        }

        #endregion

        private void PicLogo_Click(object sender, EventArgs e)
        {
            TxtUsername.Text = "UboxMaster001";
            TxtPassword.Text = "UboxMaster";
        }

        
    }
}
